$(document).ready(function(){
	var packetCommand = function() {
		this.command = -1;
		this.id = "";
		this.name = "";
		this.param = {};
	};
	var taskParam = function() {
		this.cmd = "";
		this.manager = "";
		this.task = "";
	};
	var channelParam = function() {
		this.cmd = "";
		this.channel = {};
	};
	var deviceParam = function() {
		this.cmd = "";
		this.channelid = -1;
		this.type = "";
		this.device = {};
	};
	var tagParam = function() {
		this.cmd = "";
		
		this.tag = {};
	};
	var sysConfigParam  = function() {
		this.cmd= "";
		this.config = {};
	};
	var serverConfigParam = function() {
		this.cmd = "";
		this.config = {};
	};
	var userParam = function() {
		this.cmd = "";
		this.user = {};
	};
	var Channel = function() {
		this.id = -1;
		this.name = "";
		this.desc = "";
		this.type = "";
		
	};
	var Device = function() {
		this.id = -1;
		this.channel = -1;
		this.name = "";
		this.desc = "";
		this.slaveid = 1;
		this.port = "";
		this.baudrate = 0;
		this.bytesize = 0;
		this.stopbits = 0;
		this.parity = "";
		this.timeout = 5;
		this.type = "";
		this.address = "";
	};
	var Tag = function() {
		this.id = -1;
		this.tagID = "";
		this.deviceID = -1;
		this.type = 0;
		this.name = "";
		this.desc = "";
		this.address = "";
		this.valuetype = "";
		this.swaptype = "";
		this.duration = 1000;
		this.readwrite = 0;
		this.topic = "";
		this.expression = "";
		this.K1 = 0.0;
		this.K2 = 0.0;
		this.LOLIM = 0.0;
		this.HILIM = 0.0;
		this.value = "";
		this.readtime = "";
		this.mqttID = [];
		this.span_value = "";
		this.span_time = "";

	};
	var SystemConfig = function() {
		this.ip = "";
		this.name = "";
		this.mask = "";
		this.gateway = "";
		this.dns = "";
		
	};
	var ServerConfig = function(){
		this.http = "";
		
		this.cleanlog = -1;
		this.maxlog = -1;
		
		this.sessionexpire = -1;
		this.maxupload = -1;
		
	};
	var User = function(){
		this.id = "";
		this.oriname = ""; //旧
		this.name = "";
		this.password = "";
		this.oripassword = "";	//旧密码	
		this.phone = "";
	};
	var Log = function(){
		this.type = "";
		this.time = "";
		this.content = "";
	};
	var TaskParam = function(){
		this.cmd = "";
		this.managerID = "";
		this.taskID = "";
	}
	var mqttParam = function(){
		this.cmd = "";
		this.mqttinfo = {};
	}
	var MQTTInfo = function(){
		this.id = -1;
		this.mqttid = "";
		this.name = "";
		this.url = "";
		this.user = "";
		this.pass = "";
		this.tls = 0;
		this.certfile = "";
		this.cert = "";
		this.clientid = "";

	}
	var gatewayParam = function(){
		this.cmd = "";
		this.cert = "";
	}
	var AddTagDevice = function(){
		this.id = -1;
		this.name = "";
	}
	
	var CmdTaskManager = 0;			// 0 任务管理
	var CmdRuntimeInfo =1;        	// 1 任务运行情况
	var CmdSystemInfo = 2;        	// 2 系统情况 cpu
	var CmdSystemConfig = 3;       	// 3 系统设置
	var CmdServerConfig = 4;      	// 4 服务设置
	var CmdChannel = 5;           	// 5 Channel管理
	var CmdDevice = 6;            	// 6 设备管理
	var CmdTag = 7;               	// 7 点管理
	var CmdRestartSystem = 8;   	// 8 重启系统
	var CmdRestartServer = 9;     	// 9 重启服务
	var CmdUser = 10;           	// 10 用户
	var CmdLogin = 11;            	// 11 登陆
	var CmdLog = 12;              	// 12 log
	var CmdMqtt = 13;				//13mqtt管理
	var CmdGatewayInfo = 14;		//14系统信息
	var CmdTagTest   = "tagTestRead"; 
	var CmdMQTTTest  = "mqttTestConn";
	var update = "update";      	//提交
	var query = "query";			//查
	var CmdAdd = "add";				//添加
	var CmdDel = "delete";			//删除
	var CmdStop = "stop";           //停止
	var CmdStart = "start";			//启动
	var cmdTagDevice = "tagDevice";
	var cmdTagMQTT   = "tagMQTT";
	var cmdTagValue  = "tagValue";
	var row;
	var tagArray = [];
//	WebSocket
	var id = $('#id').html();
	var name = $('#name').html();
	var ws = new ReconnectingWebSocket("ws://localhost/ws");
//	ws.debug = true;
	ws.timeoutInterval = 5400;
	ws.open();
	
	// Home timer
	var homeTimer;
	var tagTimer;
//	样式
	var h= window.screen.availHeight;
	$('.right').css("height", h-20);
	$('.navbar').css("height", h-20);
//	菜单点击换色
	$('.list-height>li>a').click(function(){
		$('.list-height>li>a').removeClass('active');
		$(this).addClass('active');
	});
//	加载
	$('.list-height>li>a').click(function(){
		$('.jiazai').show();
		$('.error').hide();
		idname = $(this).attr('id');
		ids(idname);
	});
	
	
	//连接
	ws.onmessage = function(event) {
		
		if(event.data) {
			try{
				var data = JSON.parse(event.data);
				if(data.command == CmdTag && data.cmd == CmdTagTest){
					$('#TestResult').html(data.data);
					$('#editTestResult').html(data.data);
					return;
				}
				if(data.command == CmdMqtt && data.cmd == CmdMQTTTest){
					$('#textRes').html(data.data);
					$('#editTextRes').html(data.data);
					return;
				}
				if (data.code == 0) {
					
					switch(data.command) {
						
						//系统配置
						case CmdSystemConfig:
							if(data.cmd == update){
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
									$('#systemone').next('.remove').click();
									$('#system').click();
								});
							}
							ip = data.data.ip;
							mask = data.data.mask;
							gateway = data.data.gateway;
							dns = data.data.dns;
							$('#ip').val(ip) ;
							$('#mask').val(mask);
							$('#gateway').val(gateway);
							$('#dns').val(dns);
						break;
						// 高级配置
						case CmdServerConfig:
							if(data.cmd == update){
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
									$('#systemtwo').next('.remove').click();
									$('#system').click();
								});
								
							}
							$('#http').val(data.data.http) ;
							$('#maxupload').val(data.data.maxupload);
							if(data.data.cleanlog == 1){
								$('#cleanlog1').attr("checked", true);
							}else{
								$('#cleanlog2').attr("checked", true);
							}
							$('#maxlog').val(data.data.maxlog);
							$('#session').val(data.data.sessionexpire);
							
						break;
						// 日志
						case CmdLog:
							setLogData(data.data);
						break;
						// 用户
						case CmdUser:
						if(data.cmd == update){
							$('#okModal').modal('show');
							$('#okModal .btn').click(function(){
								$('#okModal').modal('hide');
								window.location.href = 'login.html';
								
							});
							
						}
						break;
						// cpu 内存
						case CmdSystemInfo:
							$('#cpu').html(data.data.cpu +"%");
						 	$('#mem').html(data.data.mem +"%");
						 	cpu = data.data.cpu;
						 	mem = data.data.mem;
						 	changeHomeEchartValue(cpu,mem);
						break;
						// info
						case CmdGatewayInfo:
							if (data.cmd == query) {
								
								$('#serial-number').html(data.data.sn);
								$('#hardware').html(data.data.devicever);
								$('#software').html(data.data.softver);
								$('#authorization').html(data.data.license);
							}
							if(data.cmd == update){
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
								});

								initGatewayInfo();
							}
						break;
						// 系统信息
						case CmdRuntimeInfo:
							var dataRow = data.data.managers[0].tasks;
							setValueRuntimeInfo(dataRow);
						break;
						case CmdLogin:
							id = data.data.id;
							name = data.data.name;
						break;
						// mqtt
						case CmdMqtt:
							if (data.cmd == query) {
								setMqttData(data.data);
							}else{
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
								});
								initMqtt();
								
							}
						break;
						// 数据点
						case CmdTag:
						
							if (data.cmd == query) {
								setNumberTagData(data.data);
							}
							if (data.cmd == CmdAdd) {
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									// $(this).unbind();
									$('#okModal').modal('hide');
									
								});
								initNumberTag();

							}
							if (data.cmd == CmdDel) {
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									
									$('#okModal').modal('hide');
									
								});
								// $('#addTagBtn').unbind();
								initNumberTag();
								
							}
							if( data.cmd == update){
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
									
								});
								initNumberTag();
							}
							if(data.cmd == cmdTagValue){
								console.log(data.data);
								for(var n = 0;n < tagArray.length;n++) {
									var tag = tagArray[n];
									if (tag.id == data.data.id) {
										tag.value = data.data.value;
										tag.readtime = data.data.time;
										$('#'+tag.tagID).html(tag.value);
										$('#'+tag.tagID+'_time').html(tag.readtime);
									}
								}
								
							}
							if (data.cmd == cmdTagDevice){
								var row = data.data;
								var opMqttadd = '';
								var opMqttlook = '';
								
								for(var i = 0;i<row.length;i++){
									var opm = "<option value="+row[i].id+">"+row[i].name+"</option>";
									opMqttadd += opm;
									if(row[i].id == device_id){
										mqttlook = row[i].name;
										
										$('#tagLookDevice').html(mqttlook);
									}
								
								}
								$('#tagDeviceAdd').html(opMqttadd);
								$('#tagDeviceAdd').selectpicker('refresh');
								$('#tagDeviceEdit').html(opMqttadd);
								$('#tagDeviceEdit').val(device_id);
								$('#tagDeviceEdit').selectpicker('refresh');
								
								
								// for(var i = 0;i<row.length;i++){
								// 	// var opm = "<option value="+row[i].id+">"+row[i].name+"</option>";
								// 	// opMqttadd += opm;
								// 	if(row[i].id == device_id){
								// 		mqttlook = row[i].name;
										
								// 		$('#tagLookDevice').html(mqttlook);
								// 	}
									
								// }
								
								$('#tagDeviceEdit').parent().find('.filter-option').html(mqttlook);

							}
							if (data.cmd == cmdTagMQTT){
								var row = data.data	;
								var opMqttadd = '';
								var opmqttid = '';
								for(var i = 0;i<row.length;i++){
									var opm = "<option value="+row[i].id+">"+row[i].name+"</option>";
									opMqttadd += opm;
								}
								$('#tagMqttAdd').html(opMqttadd);
								$('#tagMqttAdd').selectpicker('refresh');
								$('#tagMqttEdit').html(opMqttadd);
								$('#tagMqttEdit').val(mqttid);	
								$('#tagMqttEdit').selectpicker('refresh');
								for(var j = 0;j<row.length;j++){
									for(var x=0;x<mqttid.length;x++){
										if(row[j].id == mqttid[x]){
											var mqttlook = row[j].name;
											
											var opmqtt = "("+row[j].name+")";
											opmqttid += opmqtt;
											$('#tagLookMqtt').html(opmqttid);
											
											
										}
										
									}
								
								}
							}
						break;
						// 任务
						case CmdChannel:
							if (data.cmd == query) {
								setChannelData(data.data);
							}
							if (data.cmd == update){
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
									
								});
								initChannel();
								
							}
							
						break;
						// 设备
						case CmdDevice:
							
							function deviceCodeIsOk(){
								var command = new packetCommand();
									command.command = CmdDevice;
									command.id = id;
									command.name = name;
								var param = new deviceParam();
									param.cmd = query;
									param.channelid = devicerowid;
									param.type = devicerowtype;
									param.device = {};
									command.param = param;
								var json = JSON.stringify(command);
								ws.send(json);
								
							}
							
							if (data.cmd == query) {
									setDeviceTcpData(data.data);
									setDeviceSerialData(data.data);
							}else{
								$('#okModal').modal('show');
								$('#okModal .btn').click(function(){
									$('#okModal').modal('hide');
								});
								deviceCodeIsOk();
							}
							
						break;
					}
				} else if (data.code == -1) {
					
					$('#errorModal').modal('show');
					$('#errorMessage p').html(data.data);
					$('#errorModal .btn').click(function(){
						$('#errorModal').modal('hide');
						
					});
				} else if (data.code == -2) {
					$('#loginModal').modal('show');
					$('#loginModal .btn').click(function(){
						$('#loginModal').modal('hide');
						window.location.href = 'login.html';
						
					});
				}
			} catch(err) {
				console.log(err.message);
			}
		}
	};
	ws.onerror = function(event) {
		console.log(event);
	};
	ws.onopen = function(event) {
		console.log("open");
		initGatewayInfo();
	};
	ws.onclose = function(event) {
		console.log("close");
	};
	$('#startServer').click(function(){
		var command = new packetCommand();
			command.command = CmdRestartServer;
			command.id = id;
			command.name = name;
			command.param = {};
		var json = JSON.stringify(command);
		ws.send(json);
		window.location.href = 'login.html';
	});
	$('#startSystem').click(function(){
		var command = new packetCommand();
			command.command = CmdRestartSystem;
			command.id = id;
			command.name = name;
			command.param = {};
		var json = JSON.stringify(command);
		ws.send(json);
		window.location.href = 'login.html';
	});
	
	
	//修改删除
	operateIndex = {
		//mqtt修改
		'click .MqttEdit': function (e, value, row, index) {
			$('#editTextRes').html('');
			$('#mqttSysEditModal').modal('show');
			$('#mqttSysEditModal input').next().next('.redz').addClass('hide');
			$('#mqttSysEditModal input').next('.red').addClass('hide');
			$('#editMqttName').val(row.name);
			$('#editMqttUrl').val(row.url);
			$('#editMqttUser').val(row.user);
			$('#editMqttPass').val(row.pass);
			$('#editMqttFile').val('');
			if(row.certfile){
				$('#labelName').show();
				$('#fileName')[0].innerHTML = row.certfile;
				
			}else{
				$('#labelName').hide();
			}
			$('#editMqttName,#editMqttUrl,#editMqttUser,#editMqttPass').blur(function(){
				var val = $(this).val();
				//判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				//判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#editMqttUrl').blur(function(){
				var editMqttUrl = $(this).val();
				var editUrl = /^(tcp:|ssl:)?\/\/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]):\d{0,5}$/g;
				if(editMqttUrl == ''){
					$(this).next('.red').removeClass('hide');
					$(this).next().next('.redz').addClass('hide');
				}else if(!editUrl.test(editMqttUrl)){
					$(this).next('.red').addClass('hide');
					$(this).next().next('.redz').removeClass('hide');
				}else{
					$(this).next().next('.redz').addClass('hide');
					$(this).next('.red').addClass('hide');
				}
			});
			$('.editMqttCe').click(function(){
				var editMqttName = $('#editMqttName').val();
				var editMqttUrl = $('#editMqttUrl').val();
				var editMqttUser = $('#editMqttUser').val();
				var editMqttPass = $('#editMqttPass').val();
				var editMqttFile = $('#editMqttFile').val();
				var fileName = $('#fileName').html();
				if(editMqttName == '' || editMqttUrl == '' || editMqttUser == '' || editMqttPass == ''){
					$('#mqttSysEdit input').blur();
				}else{
					$('#mqttSysEdit input').blur().unbind();
					var command = new packetCommand();
						command.command = CmdMqtt;
						command.id = id;
						command.name = name;
					var param = new mqttParam();
						param.cmd = CmdMQTTTest;
					var paramedit = new MQTTInfo();
						paramedit.id = row.id;
						paramedit.name = editMqttName;
						paramedit.url = editMqttUrl;
						paramedit.user = editMqttUser;
						paramedit.pass = editMqttPass;
						param.mqttinfo = paramedit;
						command.param = param;
					
					if(editMqttFile != ''){
						inputElement = document.getElementById('editMqttFile');
						inputList = inputElement.files;
						
						if(inputList.length > 0){
							fileName = inputList[0].name;
							var reader = new FileReader();
							reader.readAsBinaryString(inputList[0]);
							reader.onload = function loaded(evt) {
								var fileCert = $.base64.encode(evt.target.result);
							
									paramedit.pass = editMqttPass;
									paramedit.cert = fileCert;
									paramedit.tls = 1;
									paramedit.certfile = fileName;
								
								var json = JSON.stringify(command);
								ws.send(json);
							}
						}
					}else{
						
						paramedit.tls = row.tls;
						var json = JSON.stringify(command);
						ws.send(json);
					}
					
				}
			})
			$('#mqttSysEditModal .okbtn').click(function(){
				$(this).unbind();
				var editMqttName = $('#editMqttName').val();
				var editMqttUrl = $('#editMqttUrl').val();
				var editMqttUser = $('#editMqttUser').val();
				var editMqttPass = $('#editMqttPass').val();
				var editMqttFile = $('#editMqttFile').val();
				var fileName = $('#fileName').html();
				if(editMqttName == '' || editMqttUrl == '' || editMqttUser == '' || editMqttPass == ''){
					$('#mqttSysEdit input').blur();
				}else{
					$('#mqttSysEdit input').blur().unbind();
					var command = new packetCommand();
						command.command = CmdMqtt;
						command.id = id;
						command.name = name;
					var param = new mqttParam();
						param.cmd = update;
					var paramedit = new MQTTInfo();
						paramedit.id = row.id;
						paramedit.name = editMqttName;
						paramedit.url = editMqttUrl;
						paramedit.user = editMqttUser;
						paramedit.pass = editMqttPass;
						param.mqttinfo = paramedit;
						command.param = param;
					
					if(editMqttFile != ''){
						inputElement = document.getElementById('editMqttFile');
						inputList = inputElement.files;
						
						if(inputList.length > 0){
							fileName = inputList[0].name;
							var reader = new FileReader();
							reader.readAsBinaryString(inputList[0]);
							reader.onload = function loaded(evt) {
								var fileCert = $.base64.encode(evt.target.result);
							
									paramedit.pass = editMqttPass;
									paramedit.cert = fileCert;
									paramedit.tls = 1;
									paramedit.certfile = fileName;
								
								var json = JSON.stringify(command);
								ws.send(json);
							}
						}
					}else{
						
						paramedit.tls = row.tls;
						var json = JSON.stringify(command);
						ws.send(json);
					}
					$('#mqttSysEditModal').modal('hide');
					
				}
			})
		},
		'click .MqttDelete': function (e, value, row, index) {
			$('#mqttSysDelModal').modal('show');
			$('#mqttSysDelModal .okbtn').click(function(){
				$('#mqttSysDelModal').modal('hide');
				var command = new packetCommand();
					command.command = CmdMqtt;
					command.id = id;
					command.name = name;
				var param = new mqttParam();
					param.cmd = CmdDel;
					
				var paramdel = new MQTTInfo();
					paramdel.id = row.id;
					param.mqttinfo = paramdel;
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);
			})		
		},
		// 通道修改
		'click .ChannelEdit': function(e, vlaue, row, index) {
			console.log(row);
			
			$('#channelEditModal').modal('show');
			$('#channelEditModal input').next('.red').addClass('hide');
			$('#editDesc').val(row.desc);
			
			$('#editDesc').blur(function() {
				var val = $(this).val();
				// 判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				// 判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			// 提交判断
			$('#channelEditModal .okbtn').click(function(){
				$(this).unbind();
				var editDesc = $('#editDesc').val();
				console.log(row);
				if(editDesc != ''){
					var command = new packetCommand();
						command.command = CmdChannel;
						command.id = id;
						command.name = name;
					var param = new channelParam();
						param.cmd = update;
					var channeledit = new Channel();
						channeledit.id = row.id;
						channeledit.desc = editDesc;
						param.channel = channeledit;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					$('#channelEditModal').modal('hide');
					// $('#channelEditModal input').val('');
				}else{
					$('#channelEdit input').blur();
				}
			})
			
		},
		
     	// tcp设备修改
		'click .deviceTcpEdit': function (e, value, row, index) {
			$('#deviceEditTcpModal').modal('show');
			$('#deviceEditTcpModal input').next().next('.redz').addClass('hide');
			$('#deviceEditTcpModal input').next('.red').addClass('hide');
			$('#editTcpName').val(row.name);
			$('#editTcpDesc').val(row.desc);
			$('#editTcpAddress').val(row.address);
			$('#editTcpSlaveid').val(row.slaveid);
			$('#editTcpTimeout').val(row.timeout);
			$('#editTcpName,#editTcpDesc,#editTcpSlaveid,#editTcpTimeout').blur(function(){
				var val = $(this).val();
				// 判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				// 判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#editTcpAddress').blur(function(){
				var editAddress = $(this).val();
				var editUrl = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]):\d{0,5}$/g;
				if(editAddress == ''){
					$(this).next('.red').removeClass('hide');
					$(this).next().next('.redz').addClass('hide');
				}else if(!editUrl.test(editAddress)){
					$(this).next('.red').addClass('hide');
					$(this).next().next('.redz').removeClass('hide');
				}else{
					$(this).next().next('.redz').addClass('hide');
					$(this).next('.red').addClass('hide');
				}
			});
			$('#deviceEditTcpModal .okbtn').click(function(){
				$(this).unbind();
				var editTcpName = $('#editTcpName').val();
				var editTcpDesc = $('#editTcpDesc').val();
				var editTcpAddress = $('#editTcpAddress').val();
				var editTcpSlaveid = $('#editTcpSlaveid').val();
				var editTcpTimeout = $('#editTcpTimeout').val();
				if(editTcpName == '' || editTcpDesc == '' || editTcpAddress == '' || editTcpSlaveid == '' || editTcpTimeout == ''){
					$('#deviceTcpEdit input').blur();
				}else{
					$('#deviceTcpEdit input').blur().unbind();
					var command = new packetCommand();
						command.command = CmdDevice;
						command.id = id;
						command.name = name;
					var param = new deviceParam();
						param.cmd = update;
						param.channelid = devicerowid;
						param.type = devicerowtype;
					var paramedit = new Device();
						paramedit.id = row.id;
						paramedit.name = editTcpName;
						paramedit.desc = editTcpDesc;
						paramedit.slaveid = parseInt(editTcpSlaveid);
						paramedit.address = editTcpAddress;
						paramedit.timeout = parseInt(editTcpTimeout);
						param.device = paramedit;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					console.log(json);
					
					
					
				}
				$('#deviceEditTcpModal').modal('hide');
				$('#deviceTcpEdit input').val('');
				
				
			})
		},
		// tcp设备删除
		'click .deviceTcpDelete': function (e, value, row, index) {
			$('#deviceTcpDelModal').modal('show');	
			$('#deviceTcpDelModal .okbtn').click(function(){
				$('#deviceTcpDelModal').modal('hide');
				var command = new packetCommand();
					command.command = CmdDevice;
					command.id = id;
					command.name = name;
				var param = new deviceParam();
					param.cmd = CmdDel;
					param.channelid = devicerowid;
					param.type = devicerowtype;
				var paramedit = new Device();
					paramedit.id = row.id;
					param.device = paramedit;
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);
			})
			
		},
    	//  serial设备修改
		'click .deviceSerialEdit': function (e, value, row, index) {
			$('#deviceEditSerialModal').modal('show');
			$('#deviceEditSerialModal input').next('.red').addClass('hide');
			$('#editSerialName').val(row.name);
			$('#editSerialDesc').val(row.desc);
			$('#editSerialSlaveid').val(row.slaveid);
			
			$('#editSerialOvertime').val(row.timeout);
			$('#editSerialType').val(row.type);
			$('#editSerialBaudrate').val(row.baudrate);
			$('#editSerialBytesize').val(row.bytesize);
			$('#editSerialStop').val(row.stopbits);
			$('#editSerialParity').val(row.parity);

			
			$('#editSerialName,#editSerialDesc,#editSerialSlaveid,#editSerialOvertime').blur(function(){
				var val = $(this).val();
				//判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				//判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#deviceEditSerialModal .okbtn').click(function(){
				$(this).unbind();
				var editSerialName = $('#editSerialName').val();
				var editSerialDesc = $('#editSerialDesc').val();
				var editSerialSlaveid = $('#editSerialSlaveid').val();
				var editSerialOvertime = $('#editSerialOvertime').val();
				var editSerialType = $('#editSerialType option:selected').text();
				var editSerialBaudrate = $('#editSerialBaudrate option:selected').text();
				var editSerialBytesize = $('#editSerialBytesize option:selected').text();
				var editSerialStop = $('#editSerialStop option:selected').text();
				var editSerialParity = $('#editSerialParity option:selected').val();
				if(editSerialName == '' || editSerialDesc == '' || editSerialSlaveid == '' || editSerialOvertime == ''){
					$('#deviceSerialEdit input').blur();
				}else{
					$('#deviceSerialEdit input').blur().unbind();
					var command = new packetCommand();
					command.command = CmdDevice;
						command.id = id;
						command.name = name;
					var param = new deviceParam();
						param.cmd = update;
						param.channelid = devicerowid;
						param.type = devicerowtype;
					var paramedit = new Device();
						paramedit.id = row.id;
						paramedit.name = editSerialName;
						paramedit.desc = editSerialDesc;
						paramedit.type = editSerialType;
						paramedit.slaveid = parseInt(editSerialSlaveid);
						paramedit.baudrate = parseInt(editSerialBaudrate);
						paramedit.bytesize = parseInt(editSerialBytesize);
						paramedit.stopbits = parseInt(editSerialStop);
						paramedit.parity = editSerialParity;
						paramedit.timeout = parseInt(editSerialOvertime);
						param.device = paramedit;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					$('#deviceEditSerialModal').modal('hide');
					$('#deviceEditSerialModal input').val('');
				}
			});

		},
		// serial设备删除
		'click .deviceSerialDelete': function (e, value, row, index) {
			$('#deviceSerialDelModal').modal('show');	
			$('#deviceSerialDelModal .okbtn').click(function(){
				$('#deviceSerialDelModal').modal('hide');
				var command = new packetCommand();
					command.command = CmdDevice;
					command.id = id;
					command.name = name;
				var param = new deviceParam();
					param.cmd = CmdDel;
					param.channelid = devicerowid;
					param.type = devicerowtype;
				var paramedit = new Device();
					paramedit.id = row.id;
					param.device = paramedit;
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);
			})	
		},
		// 数据点查看
		'click .numberTagDetail': function (e, value, row, index) {
			// console.log(row);
			$("#tagLookModal").modal('show');
			$('#tagLookName').html(row.name);
			$('#tagLookDesc').html(row.desc);
			
			$('#tagLookCode').html(row.address);
			$('#tagLookTopic').html(row.topic);
			
			$('#tagLookSort').html(row.swaptype);
			
			$('#tagLookPing').html(row.duration);
			if(row.ReadWrite == 1){
				$('#tagLookRead').html("可读/可写");
			}else if(row.ReadWrite == 0){
				$('#tagLookRead').html("只读");
			}
			if(row.type == 0){
				$('#tagLookType').html("IO点");
			}else if(row.ReadWrite == 1){
				$('#tagLookType').html("内存点");
			}
			if(row.deviceID.length != ''){
				device_id = row.deviceID;
				function deviceLook(device_id){
					
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = cmdTagDevice;
						
						param.tag = {};
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
				}
				deviceLook(device_id);
				
			}else{
				$('#tagLookDevice').html("不属任何设备");
			}
			if(row.mqttID.length > 0){
				mqttid = row.mqttID;
				function mqtt_id(mqttid){
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = cmdTagMQTT;
						param.tag = {};
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
				}
				mqtt_id(mqttid);
				
			}else{
				$('#tagLookMqtt').html("未绑定");
			}
			$('#tagLookModal .okbtn').click(function(){
				$(this).unbind();
				$("#tagLookModal").modal('hide');
			});
			
			
			
		},
		// 数据点修改
		'click .numberTagEdit': function (e, value, row, index) {
			
			$("#tagEditModal").modal('show');
			$('#tagEditModal input').next('.red').addClass('hide');
			var command = new packetCommand();
				command.command = CmdTag;
				command.id = id;
				command.name = name;
			var param = new tagParam();
				param.cmd = cmdTagDevice;
				param.tag = {};
				command.param = param;
			var json = JSON.stringify(command);
			ws.send(json);
			var command = new packetCommand();
				command.command = CmdTag;
				command.id = id;
				command.name = name;
			var param = new tagParam();
				param.cmd = cmdTagMQTT;
				param.tag = {};
				command.param = param;
			var json = JSON.stringify(command);
			ws.send(json);
			$('#tagEditModal input').val('');
			$('#tagNameEdit').val(row.name);
			$('#tagDescEdit').val(row.desc);
			
			$('#tagSelfCodeEdit').val(row.address);
			$('#tagTopicEdit').val(row.topic);
			$('#tagReadEdit').val(row.ReadWrite);
			$('#tagValueTypeEdit').val(row.valuetype);
			$('#tagTypeEdit').val(row.type);
			$('#tagSortEdit').val(row.swaptype);
			$('#tagPingEdit').val(row.duration);
			$('#tagK1Edit').val(row.K1);
			$('#tagK2Edit').val(row.K2);
			$('#tagHilimEdit').val(row.HILIM);
			$('#tagLolimEdit').val(row.LOLIM);
			$('#tagExpresEdit').val(row.expression);
			$('#tagDeviceEdit').val(row.deviceID);
			var typeval = $('#tagSortEdit').val(row.swaptype);
			
			if(row.valuetype.indexOf("8") > 0 || row.valuetype.indexOf("16") > 0){
				$('#tagSortEdit').html('<option value="AB" class="sortOne">AB</option><option value="BA" class="sortOne">BA</option>');
			}
			if(row.valuetype.indexOf("32") > 0 || row.valuetype.indexOf("float") > 0){
				$('#tagSortEdit').html('<option value="ABCD" class="sortTwo">ABCD</option><option value="BADC" class="sortTwo">BADC</option><option value="CDAB" class="sortTwo">CDAB</option><option value="DCBA" class="sortTwo">DCBA</option>');
			}
			if(row.valuetype.indexOf("64") > 0 || row.valuetype.indexOf("dou") > 0){
				$('#tagSortEdit').html('<option value="ABCDEFGH" class="sortThr">ABCDEFGH</option><option value="GHEFCDAB" class="sortThr">GHEFCDAB</option><option value="BADCFEHG" class="sortThr">BADCFEHG</option><option value="HGFEDCBA" class="sortThr">HGFEDCBA</option>');
			}
			
			// if(row.deviceID.length != ''){
				device_id = row.deviceID;
				function deviceVal(device_id){
					
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = cmdTagDevice;
						
						param.tag = {};
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
				}
				deviceVal(device_id);
				
			// }else{
			// 	$('#tagDeviceEdit').parent().find('.filter-option').html('');
			// }
			
			mqttid = row.mqttID;
			function mqtt_id(mqttid){
				var command = new packetCommand();
					command.command = CmdTag;
					command.id = id;
					command.name = name;
				var param = new tagParam();
					param.cmd = cmdTagMQTT;
					param.tag = {};
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);
				
			}
			mqtt_id(mqttid);
			// 	$('#tagMqttEdit').parent().find('.filter-option').html('');
			$('#tagEditModal input').blur(function(){
				var val = $(this).val();
				//判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				//判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#tagValueTypeEdit').blur(function(){
				var typeval = $(this).val();
				$("#tagSortEdit").empty(); 
				if(typeval.indexOf("8") > 0 || typeval.indexOf("16") > 0){
					$('#tagSortEdit').html('<option value="AB" class="sortOne">AB</option><option value="BA" class="sortOne">BA</option>');
				}
				if(typeval.indexOf("32") > 0 || typeval.indexOf("float") > 0){
					$('#tagSortEdit').html('<option value="ABCD" class="sortTwo">ABCD</option><option value="BADC" class="sortTwo">BADC</option><option value="CDAB" class="sortTwo">CDAB</option><option value="DCBA" class="sortTwo">DCBA</option>');
				}
				if(typeval.indexOf("64") > 0 || typeval.indexOf("dou") > 0){
					$('#tagSortEdit').html('<option value="ABCDEFGH" class="sortThr">ABCDEFGH</option><option value="GHEFCDAB" class="sortThr">GHEFCDAB</option><option value="BADCFEHG" class="sortThr">BADCFEHG</option><option value="HGFEDCBA" class="sortThr">HGFEDCBA</option>');
				}
			})
			
			$('.editCheckbtn').click(function(){
				// $(this).unbind();
				var tagNameEdit = $('#tagNameEdit').val();
				var tagDescEdit = $('#tagDescEdit').val();
				var tagDeviceEdit = parseInt($('#tagDeviceEdit option:selected').val());
				var tagSelfCodeEdit = $('#tagSelfCodeEdit').val();
				var tagTopicEdit = $('#tagTopicEdit').val();
				var tagReadEdit = parseInt($('#tagReadEdit option:selected').val());
				var tagValueTypeEdit = $('#tagValueTypeEdit option:selected').val();
				var tagTypeEdit = parseInt($('#tagTypeEdit option:selected').val());
				var tagSortEdit = $('#tagSortEdit option:selected').val();
				var tagPingEdit = parseInt($('#tagPingEdit').val());
				var tagK1Edit = parseInt($('#tagK1Edit').val());
				var tagK2Edit = parseInt($('#tagK2Edit').val());
				var tagHilimEdit = parseInt($('#tagHilimEdit').val());
				var tagLolimEdit = parseInt($('#tagLolimEdit').val());
				var tagExpresEdit = $('#tagExpresEdit').val();
				if($('#tagMqttEdit').val() == null){
					tagMqttEdit = [];
				}else{
					stringArray = $('#tagMqttEdit').val().toString().split(',');
					rowArray = [];
					for(var i=0;i<stringArray.length;i++){
						mqtt = parseInt(stringArray[i]);
						rowArray.push(mqtt);
	
					}
					tagMqttEdit = rowArray;
					
				}
				if(tagNameEdit == '' || tagSelfCodeEdit == '' || tagTopicEdit == ''){
					$('#tagEditModal input').blur();
					
				}else{
					$('#tagEditModal input').blur().unbind();
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = CmdTagTest;
					var tagedit = new Tag();
						tagedit.id = row.id;
						tagedit.deviceID = tagDeviceEdit;
						tagedit.type = tagTypeEdit;
						tagedit.name = tagNameEdit;
						tagedit.desc = tagDescEdit;
						tagedit.address = tagSelfCodeEdit;
						tagedit.valuetype = tagValueTypeEdit;
						tagedit.swaptype = tagSortEdit;
						tagedit.duration = tagPingEdit;
						tagedit.readwrite = tagReadEdit;
						tagedit.topic = tagTopicEdit;
						tagedit.expression = tagExpresEdit;
						tagedit.K1 = tagK1Edit;
						tagedit.K2 = tagK2Edit;
						tagedit.LOLIM = tagLolimEdit;
						tagedit.HILIM = tagHilimEdit;
						tagedit.mqttID = tagMqttEdit;
		
						param.tag = tagedit;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					
				}
				
			})
			$('#tagEditModal .okbtn').click(function(){
				$(this).unbind();
				var tagNameEdit = $('#tagNameEdit').val();
				var tagDescEdit = $('#tagDescEdit').val();
				var tagDeviceEdit = parseInt($('#tagDeviceEdit option:selected').val());
				var tagSelfCodeEdit = $('#tagSelfCodeEdit').val();
				var tagTopicEdit = $('#tagTopicEdit').val();
				var tagReadEdit = parseInt($('#tagReadEdit option:selected').val());
				var tagValueTypeEdit = $('#tagValueTypeEdit option:selected').val();
				var tagTypeEdit = parseInt($('#tagTypeEdit option:selected').val());
				var tagSortEdit = $('#tagSortEdit option:selected').val();
				var tagPingEdit = parseInt($('#tagPingEdit').val());
				var tagK1Edit = parseInt($('#tagK1Edit').val());
				var tagK2Edit = parseInt($('#tagK2Edit').val());
				var tagHilimEdit = parseInt($('#tagHilimEdit').val());
				var tagLolimEdit = parseInt($('#tagLolimEdit').val());
				var tagExpresEdit = $('#tagExpresEdit').val();
				if($('#tagMqttEdit').val() == null){
					tagMqttEdit = [];
				}else{
					stringArray = $('#tagMqttEdit').val().toString().split(',');
					rowArray = [];
					for(var i=0;i<stringArray.length;i++){
						mqtt = parseInt(stringArray[i]);
						rowArray.push(mqtt);
	
					}
					tagMqttEdit = rowArray;
					
				}
				if(tagNameEdit == '' || tagSelfCodeEdit == '' || tagTopicEdit == ''){
					$('#tagEditModal input').blur();
					
				}else{
					$('#tagEditModal input').blur().unbind();
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = update;
					var tagedit = new Tag();
						tagedit.id = row.id;
						tagedit.deviceID = tagDeviceEdit;
						tagedit.type = tagTypeEdit;
						tagedit.name = tagNameEdit;
						tagedit.desc = tagDescEdit;
						tagedit.address = tagSelfCodeEdit;
						tagedit.valuetype = tagValueTypeEdit;
						tagedit.swaptype = tagSortEdit;
						tagedit.duration = tagPingEdit;
						tagedit.readwrite = tagReadEdit;
						tagedit.topic = tagTopicEdit;
						tagedit.expression = tagExpresEdit;
						tagedit.K1 = tagK1Edit;
						tagedit.K2 = tagK2Edit;
						tagedit.LOLIM = tagLolimEdit;
						tagedit.HILIM = tagHilimEdit;
						tagedit.mqttID = tagMqttEdit;
		
						param.tag = tagedit;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					// console.log(json);
					$("#tagEditModal").modal('hide');
					$("#tagEditModal input").val('');
				}
	
			})
			
		},
		//数据点删除
		'click .numberTagDelete': function (e, value, row, index) {
			$("#tagDelModal").modal('show');
			$("#tagDelModal .okbtn").click(function(){
				$("#tagDelModal .okbtn").unbind();
				var command = new packetCommand();
					command.command = CmdTag;
					command.id = id;
					command.name = name;
				var param = new tagParam();
					param.cmd = CmdDel;
				var tagdel = new Tag();
					tagdel.id = row.id;
					param.tag = tagdel;
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);	
				$("#tagDelModal").modal('hide');	
			})
			
		},
    	
    };	
	
	//首页调用echart
	function initHomeTimer() {
		if(homeTimer == undefined) {
			homeTimer = setInterval(function(){
			// echart
			var command = new packetCommand();
				command.command = CmdSystemInfo;
				command.id = id;
			   	command.name = name;
			   	command.param = {};
		   	var json = JSON.stringify(command);
			   ws.send(json);
		 
			}, 1000);
		}
	}
	initHome();
	initHomeTimer();
	
	function initGatewayInfo(){
		var command = new packetCommand();
			command.command = CmdGatewayInfo;
			command.id = id;
			command.name = name;
		var param = new gatewayParam();
			param.cmd = query;
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
		$('#upgrade').click(function(){
			$('#upgradeModal').modal('show');
			$('#upgradeModal .okbtn').click(function(){
				$(this).unbind();
				var upgradeFile = $('#upgradeFile').val();
				var command = new packetCommand();
					command.command = CmdGatewayInfo;
					command.id = id;
					command.name = name;
				var param = new gatewayParam();
					param.cmd = update;
					command.param = param;
				if(upgradeFile != ''){
					upgradeElement = document.getElementById('upgradeFile');
					upgradeList = upgradeElement.files;
					if(upgradeList.length > 0){
						fileName = upgradeList[0].name;
						var reader = new FileReader();
						reader.readAsBinaryString(upgradeList[0]);
						reader.onload = function loaded(evt) {
							var fileCert = evt.target.result;
								
							param.cert = fileCert;
							var json = JSON.stringify(command);
							ws.send(json);
							
						}
						
					}
					
				}else{
					var json = JSON.stringify(command);
					ws.send(json);
					
					
				}
				$('#upgradeFile').val("");
				$('#upgradeModal').modal('hide');
			})
		})
		
	}
	initGatewayInfo();
	
	//系统配置
	function initSystemConfig(){
		//	系统配置查询
		var command = new packetCommand();
			command.command = CmdSystemConfig;
			command.id = id;
			command.name = name;
		var param = new sysConfigParam();
			param.cmd = query;
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
		//系统配置上传判断
		$('#ip,#mask,#gateway,#dns').blur(function() {
			var val = $(this).val();
			var resip = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/g;
			//判断不为空
			if(val == '') {
				$(this).next('.red').removeClass('hide');
				$(this).next().next('.redz').addClass('hide');
			//判断正则
			}else if(!resip.test(val)){
				$(this).next('.red').addClass('hide');
				$(this).next().next('.redz').removeClass('hide');
			}else{
				$(this).next().next('.redz').addClass('hide');
				$(this).next('.red').addClass('hide');
			}
		});
		//	系统配置上传传值
		$("#systemone").click(function(){
			var ip = $('#ip').val() ;
			var mask = $('#mask').val();
			var gateway = $('#gateway').val();
			var dns = $('#dns').val();
			
			if(ip == '' || mask =='' || gateway == '' || dns == ''){
				$('.systemCon input').blur();
			}else{
				var command = new packetCommand();
					command.command = CmdSystemConfig;
					command.id = id;
					command.name = name;
				var param = new sysConfigParam();
					param.cmd = update;
					
				var params = new SystemConfig();
					params.name = name;
					params.ip = $('#ip').val();
					params.mask = $('#mask').val();
					params.gateway = $('#gateway').val();
					params.dns = $('#dns').val();
					
					param.config = params;
					command.param = param;
					console.log(command);
				var json = JSON.stringify(command);
				ws.send(json);
			}
		});
		//	高级配置
		//	高级配置查找
		var command = new packetCommand();
			command.command = CmdServerConfig;
			command.id = id;
			command.name = name;
		var param = new serverConfigParam();
			param.cmd = query;
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
		//	高级配置上传判断
		$('#maxupload,#maxlog,#session').blur(function() {
			var val = $(this).val();
			var numb = /^(\d{1,}|\*)$/g;
			
			//	判断不为空
			if(val == '') {
				$(this).next('.red').removeClass('hide');
				$(this).next().next('.redz').addClass('hide');
			//	判断正则
			}else if(!numb.test(val)){
					$(this).next('.red').addClass('hide');
					$(this).next().next('.redz').removeClass('hide');
			}else{
				$(this).next().next('.redz').addClass('hide');
				$(this).next('.red').addClass('hide');
			}
		});
		$('#http').blur(function(){
			var http = $('#http').val();
			var https = /^(^[1-9]\d{0,3}$)|(^[1-5]\d{4}$)|(^6[0-4]\d{3}$)|(^65[0-4]\d{2}$)|(^655[0-2]\d$)|(^6553[0-5]$)$/g;
			if(http == ''){
				$(this).next('.red').removeClass('hide');
				$(this).next().next('.redz').addClass('hide');
			}else if(!https.test(http)){
				$(this).next('.red').addClass('hide');
				$(this).next().next('.redz').removeClass('hide');
			}else{
				$(this).next().next('.redz').addClass('hide');
				$(this).next('.red').addClass('hide');
			}
		
		})
		//	高级配置上传传值
		$("#systemtwo").click(function(){
			var http = $('#http').val();
			var maxupload = $('#maxupload').val();
			var maxlog = $('#maxlog').val();
			var session = $('#session').val();
			if(http == '' || maxupload == '' || maxlog == '' || session == ''){
				$('.serverCon input').blur();
			}else{
				var command = new packetCommand();
					command.command = CmdServerConfig;
					command.id = id;
					command.name = name;
				var param = new serverConfigParam();
					param.cmd = update;
					
				var params = new ServerConfig();
					params.http = $('#http').val() ;
					params.cleanlog = parseInt($('input:radio[name="cleanlog"]:checked').val());
					params.maxupload = parseInt($('#maxupload').val());
					params.maxlog = parseInt($('#maxlog').val());
					params.sessionexpire = parseInt($('#session').val());
					param.config = params;
					command.param = param;
					console.log(command);
				var json = JSON.stringify(command);
				console.log(json);
				ws.send(json);
			}
			
		});
	}
	// 用户管理
	function initUser(){
		$('#yuanuser').html(name);
		var command = new packetCommand();
			command.command = CmdUser;
			command.id = id;
			command.name = name;
		var param = new User();
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
		$('#oripassword,#xinname,#password1,#password2').blur(function() {
			val = $(this).val();
			
			//判断不为空
			if(val == '') {
				$(this).next('.red').removeClass('hide');
				$(this).next().next('.redz').addClass('hide');
			//判断正则
			}else if($('#password1').val() != $('#password2').val()){
				$(this).next('.red').addClass('hide');
				$(this).next().next('.redz').removeClass('hide');
			}else{
				$(this).next().next('.redz').addClass('hide');
				$(this).next('.red').addClass('hide');
			}
		
		});
		$('#useradmin').click(function(){
			var oripassword = $('#oripassword').val();
			var xinname = $('#xinname').val();
			var password1 = $('#password1').val();
			var password2 = $('#password2').val();
			
			if(oripassword == '' || xinname == '' || password1 == '' || password2 == ''){
				$('.userUpload input').blur();
			}else{
				var command = new packetCommand();
					command.command = CmdUser;
					command.id = id;
					command.name = name;
       			var param = new userParam();
       				param.cmd = update;
       			var params = new User();	
       				params.oriname = name;
       				params.oripassword = $.md5($('#oripassword').val());
       				params.name = $('#xinname').val();
					params.password = $.md5($('#password1').val());
					param.user = params;
					command.param = param;
				var json = JSON.stringify(command);
				console.log(json);
				ws.send(json);
			}
		})
	}
	
	//mqtt修改按钮
	function mqttSysEditDelete(value, row, index) {
		return [
	      	'<button type="button" class="MqttEdit btn btn-warning remove " style="margin-right:15px;">修改</button>',
	      	'<button type="button" class="MqttDelete btn btn-warning btn-danger remove " style="margin-right:15px;">删除</button>'
	    ].join('');
	}
	// 通道修改删除
	function channelEditDelete(value, row, index) {
		return [
	      	'<button type="button" class="ChannelEdit btn btn-warning remove " style="margin-right:15px;">修改</button>',
	      	
	    ].join('');
	}
	// tcp修改删除
	function deviceTcpEditDelete(value, row, index) {
		return [
	      	'<button type="button" class="deviceTcpEdit btn btn-warning remove " style="margin-right:15px;">修改</button>',
	      	'<button type="button" class="deviceTcpDelete btn btn-warning btn-danger remove " style="margin-right:15px;">删除</button>'
	    ].join('');
	}
	// serial修改删除
	function deviceSerialEditDelete(value, row, index) {
		return [
	      	'<button type="button" class="deviceSerialEdit btn btn-warning remove " style="margin-right:15px;">修改</button>',
	      	'<button type="button" class="deviceSerialDelete btn btn-warning btn-danger remove " style="margin-right:15px;">删除</button>'
	    ].join('');
	}
	// 数据点修改删除
	function tagEditDelete(value, row, index) {
		return [
			'<span class="numberTagDetail"><i class="fa fa-arrow-circle-right" style="color:#1A4F95;font-size:22px;"></i></span>',
	      	'<button type="button" class="numberTagEdit btn btn-warning remove " style="margin-right:15px;">修改</button>',
	      	'<button type="button" class="numberTagDelete btn btn-warning btn-danger remove " style="margin-right:15px;">删除</button>'
	    ].join('');
	}

	//mqtt管理
	function initMqtt(){
		$('#mqtt-table').bootstrapTable({
			//toolbar: '#toolbar',
            method : 'post',
			//contentType : "application/x-www-form-urlencoded",
            //url : 'query',
			//是否禁用ajax缓存
            cache : false,
			//高
			//height : h-340,
			//隔行变色
            striped : true,
			//显示分页
            pagination : true,
			//默认显示条数
            pageSize : 10,
			//先显示的页码
            pageNumber : 1,
			//可以选择的条数
            pageList : [ 10, 20, 50, 100, 200, 500 ],
			//是否显示列头
            showHeader:true,
			//是否显示列脚
            showFooter:false,
			//是否显示内容列下拉框
            showColumns : true,
			//是否显示内容列刷新
            showRefresh :true,
			//是否切换显示视图
            // showToggle:true,
			//切换显示条数页码框
            showPaginationSwitch:false,
			//按钮显示左右
            buttonsAlign:'right',
			//搜索
            search : true,
			//搜索显示左右
            searchAlign:'left',
			//页码显示上下
            paginationVAlign:'bottom',
            
            iconsPrefix:'glyphicon',
            icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
            clickToSelect : true,
            columns : [ {
            	field : "name",
                title : "名称",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "url",
                title : "地址",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "user",
                title : "用户名",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "pass",
                title : "密码",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "tls",
                title : "TLS/SSL",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
			//	field : "handle",
	            title : "操作",
	            align : "center",
	            valign : "middle",
	            events: operateIndex,
	        	formatter: mqttSysEditDelete
            }],
            data : [],
            onPageChange : function(size, number) {
                $("#pageSizeInput").val(size);
                $("#pageNumberInput").val(number);
                var form = $('#tableForm');
                form.action = 'query';
                form.submit();
            },
            
            formatNoMatches : function() {
                return '无符合条件的记录';
            }
		});
		var command = new packetCommand();
			command.command = CmdMqtt;
			command.id = id;
			command.name = name;
		var param = new mqttParam();
			param.cmd = query;
			param.mqttinfo = {};
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
        $('#addMqttBtn').click(function(){
			$('#textRes').html("");
			$('#mqttSysAddModal').modal('show');
			$('#mqttSysAdd input').next().next('.redz').addClass('hide');
			$('#mqttSysAdd input').next('.red').addClass('hide');
			$('#addMqttName,#addMqttUrl,#addMqttUser,#addMqttPass').blur(function(){
				var val = $(this).val();
				//判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				//判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#addMqttUrl').blur(function(){
				var addMqttUrl = $(this).val();
				var addUrl = /^(tcp:|ssl:)?\/\/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]):\d{0,5}$/g;
				if(addMqttUrl == ''){
					$(this).next('.red').removeClass('hide');
					$(this).next().next('.redz').addClass('hide');
				}else if(!addUrl.test(addMqttUrl)){
					$(this).next('.red').addClass('hide');
					$(this).next().next('.redz').removeClass('hide');
				}else{
					$(this).next().next('.redz').addClass('hide');
					$(this).next('.red').addClass('hide');
				}
			});
			$('.addMqttCe').click(function(){
				var addMqttName = $('#addMqttName').val();
				var addMqttUrl = $('#addMqttUrl').val();
				var addMqttUser = $('#addMqttUser').val();
				var addMqttPass = $('#addMqttPass').val();
				var addMqttFile = $('#addMqttFile').val();
				var addMqttClientID = $('#addMqttClientID').val();
				if(addMqttName == '' || addMqttUrl == '' || addMqttUser == '' || addMqttPass == ''){
					$('#mqttSysAdd input').blur();
				}else{
					var command = new packetCommand();
						command.command = CmdMqtt;
						command.id = id;
						command.name = name;
					var param = new mqttParam();
						param.cmd = CmdMQTTTest;
					var paramadd = new MQTTInfo();
						paramadd.name = addMqttName;
						paramadd.url = addMqttUrl;
						paramadd.user = addMqttUser;
						paramadd.pass = addMqttPass;
						paramadd.clientid = addMqttClientID;
						param.mqttinfo = paramadd;
						command.param = param;
					
					if(addMqttFile != ''){
						inputElement = document.getElementById('addMqttFile');
						inputList = inputElement.files;
						if(inputList.length > 0){
							fileName = inputList[0].name;
							var reader = new FileReader();
							reader.readAsBinaryString(inputList[0]);
							reader.onload = function loaded(evt) {
								var fileCert = $.base64.encode(evt.target.result);
									paramadd.pass = addMqttPass;
									paramadd.cert = fileCert;
									paramadd.tls = 1;
									paramadd.certfile = fileName;
								
								var json = JSON.stringify(command);
								ws.send(json);
							}
						}
					}else{
						paramadd.tls = 0;
						var json = JSON.stringify(command);
						ws.send(json);
					}
					
				}
			})
			$('#mqttSysAddModal .okbtn').click(function(){

				var addMqttName = $('#addMqttName').val();
				var addMqttUrl = $('#addMqttUrl').val();
				var addMqttUser = $('#addMqttUser').val();
				var addMqttPass = $('#addMqttPass').val();
				var addMqttFile = $('#addMqttFile').val();
				var addMqttClientID = $('#addMqttClientID').val();
				if(addMqttName == '' || addMqttUrl == '' || addMqttUser == '' || addMqttPass == ''){
					$('#mqttSysAdd input').blur();
				}else{
					var command = new packetCommand();
						command.command = CmdMqtt;
						command.id = id;
						command.name = name;
					var param = new mqttParam();
						param.cmd = CmdAdd;
					var paramadd = new MQTTInfo();
						paramadd.name = addMqttName;
						paramadd.url = addMqttUrl;
						paramadd.user = addMqttUser;
						paramadd.pass = addMqttPass;
						paramadd.clientid = addMqttClientID;
						param.mqttinfo = paramadd;
						command.param = param;
					
					if(addMqttFile != ''){
						inputElement = document.getElementById('addMqttFile');
						inputList = inputElement.files;
						if(inputList.length > 0){
							fileName = inputList[0].name;
							var reader = new FileReader();
							reader.readAsBinaryString(inputList[0]);
							reader.onload = function loaded(evt) {
								var fileCert = $.base64.encode(evt.target.result);
									paramadd.pass = addMqttPass;
									paramadd.cert = fileCert;
									paramadd.tls = 1;
									paramadd.certfile = fileName;
								
								var json = JSON.stringify(command);
								ws.send(json);
							}
						}
					}else{
						paramadd.tls = 0;
						var json = JSON.stringify(command);
						ws.send(json);
					}
					$('#mqttSysAddModal').modal('hide');
					$('#mqttSysAdd input').val('');
				}
			})
		});
	}
	function setMqttData(data){
		$('#mqtt-table').bootstrapTable('load', data);
	}
	//任务表
	function initChannel(){
		$('#task-table').bootstrapTable({
	        method : 'post',
	        contentType : "application/x-www-form-urlencoded",
	        //url : 'query',
			// 是否禁用ajax缓存
	        cache : false,
			// 高
			//height : h-340,
			//隔行变色
	        striped : true,
			//显示分页
	        pagination : true,
			// 默认显示条数
	        pageSize : 10,
			//先显示的页码
	        pageNumber : 1,
			//可以选择的条数
	        pageList : [ 10, 20, 50, 100, 200, 500 ],
			//是否显示列头
	        showHeader:true,
			//是否显示列脚
	        showFooter:false,
			//是否显示内容列下拉框
	        showColumns : true,
			//是否显示内容列刷新
	        // showRefresh :true,
			//是否切换显示视图
	        showToggle:true,
			//切换显示条数页码框
	        showPaginationSwitch:false,
			//按钮显示左右
	        buttonsAlign:'right',
			//搜索
	        search : true,
			//搜索显示左右
	        searchAlign:'left',
			//页码显示上下
	        paginationVAlign:'bottom',
	        
	        iconsPrefix:'glyphicon',
	        icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
	        clickToSelect : true,
	        columns : [ {
	            field : "name",
	            title : "名称",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "desc",
	            title : "描述",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        
	        }, {
	            field : "type",
	            title : "类型",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        
	        }, {
	            // field : "handle",
	            title : "操作",
	            align : "center",
	            valign : "middle",
	            events: operateIndex,
	        	formatter: channelEditDelete
	        } ],
	        data : [],
	        onPageChange : function(size, number) {
	            $("#pageSizeInput").val(size);
	            $("#pageNumberInput").val(number);
	            var form = $('#tableForm');
	            form.action = 'query';
	            form.submit();
	        },
	        
	        formatNoMatches : function() {
	            return '无符合条件的记录';
	        },
	        onDblClickRow : function(row, $element){
	        	if(row.type == "tcp"){
	        		devicerowid = row.id;
					devicerowtype = row.type;
					deviceName = row.name;
	        		task('task-device',row.type,deviceName);
	        		$('#task-device').removeClass('hide');
					initDeviceTcp();
	        	}
	        	if(row.type == "serial"){
					devicerowid = row.id;
					devicerowtype = row.type;
					deviceName = row.name;
	        		task('task-device',row.type,deviceName);
	        		$('#task-device').removeClass('hide');
	        		initDeviceSerial();
	        	}
        		var command = new packetCommand();
					command.command = CmdDevice;
					command.id = id;
					command.name = name;
				var param = new deviceParam();
					param.cmd = query;
					param.channelid = row.id;
					param.type = row.type;
					param.device = {};
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);

	        	
	        	
	        }
		});
		
		var command = new packetCommand();
			command.command = CmdChannel;
			command.id = id;
			command.name = name;
		var param = new channelParam();
			param.cmd = query;
			param.channel = {};
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
	}
	//任务表格加载数据
	function setChannelData(data){
		$('#task-table').bootstrapTable('load', data);
		
	}
	//tcp设备表
	function initDeviceTcp(){
		$('.deviceSerial').addClass('hide');
		$('#deviceTcpTable').bootstrapTable({
	        method : 'post',
	        contentType : "application/x-www-form-urlencoded",
	        //url : 'query',
			//是否禁用ajax缓存
	        cache : false,
			//高
			//height : h-340,
			//隔行变色
	        striped : true,
	        // 显示分页
	        pagination : true,
	        // 默认显示条数
	        pageSize : 10,
	    	// 先显示的页码
	        pageNumber : 1,
	        // 可以选择的条数
	        pageList : [ 10, 20, 50, 100, 200, 500 ],
	    	// 是否显示列头
	        showHeader:true,
			// 是否显示列脚
	        showFooter:false,
			// 是否显示内容列下拉框
	        showColumns : true,
			// 是否显示内容列刷新
	        // showRefresh :true,
			// 是否切换显示视图
	        showToggle:true,
			// 切换显示条数页码框
	        showPaginationSwitch:false,
	    	// 按钮显示左右
	        buttonsAlign:'right',
	    	//  搜索
	        search : true,
			//搜索显示左右
	        searchAlign:'left',
			//页码显示上下
	        paginationVAlign:'bottom',
	        
	        iconsPrefix:'glyphicon',
	        icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
	        clickToSelect : true,
	        columns : [ {
	            field : "name",
	            title : "名称",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "desc",
	            title : "描述",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "slaveid",
	            title : "从机号",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "address",
	            title : "地址",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "timeout",
	            title : "超时",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            // field : "handle",
	            title : "操作",
	            align : "center",
	            valign : "middle",
	            events: operateIndex,
	        	formatter: deviceTcpEditDelete
	        } ],
	        data : [],
	        onPageChange : function(size, number) {
	            $("#pageSizeInput").val(size);
	            $("#pageNumberInput").val(number);
	            var form = $('#tableForm');
	            form.action = 'query';
	            form.submit();
	        },
	        
	        formatNoMatches : function() {
	            return '无符合条件的记录';
	        },
	        
	    });
		
		$('#tcpDeviceAdd').click(function(){
			$('#deviceAddTcpModal').modal('show');
			$('#deviceAddTcpModal input').next().next('.redz').addClass('hide');
			$('#deviceAddTcpModal input').next('.red').addClass('hide');
			
		});
		$('#addTcpName,#addTcpDesc,#addTcpSlaveid,#addTcpTimeout,#addTcpWeb').blur(function(){
			var val = $(this).val();
			//判断不为空
			if(val == '') {
				$(this).next('.red').removeClass('hide');
			//判断正则
			}else{
				$(this).next('.red').addClass('hide');
			}
		});
		$('#addTcpAddress').blur(function(){
			var addAddress = $(this).val();
			var addUrl = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/g;
			if(addAddress == ''){
				$(this).next('.red').removeClass('hide');
				$(this).next().next('.redz').addClass('hide');
			}else if(!addUrl.test(addAddress)){
				$(this).next('.red').addClass('hide');
				$(this).next().next('.redz').removeClass('hide');
			}else{
				$(this).next().next('.redz').addClass('hide');
				$(this).next('.red').addClass('hide');
			}
		});
		$('#deviceAddTcpModal .okbtn').click(function(){
			
			var addTcpName = $('#addTcpName').val();
			var addTcpDesc = $('#addTcpDesc').val();
			var addTcpAddress = $('#addTcpAddress').val()+':'+$('#addTcpWeb').val();
			var addTcpSlaveid = $('#addTcpSlaveid').val();
			var addTcpTimeout = $('#addTcpTimeout').val();
			if(addTcpName == '' || addTcpDesc == '' || addTcpAddress == '' || addTcpSlaveid == '' || addTcpTimeout == ''){
				$('#deviceTcpAdd input').blur();
			}else{
				
				var command = new packetCommand();
					command.command = CmdDevice;
					command.id = id;
					command.name = name;
				var param = new deviceParam();
					param.cmd = CmdAdd;
					param.channelid = devicerowid;
					param.type = devicerowtype;
				var paramadd = new Device();
					paramadd.name = addTcpName;
					paramadd.desc = addTcpDesc;
					paramadd.slaveid = parseInt(addTcpSlaveid);
					paramadd.address = addTcpAddress;
					paramadd.timeout = parseInt(addTcpTimeout);
					param.device = paramadd;
					command.param = param;
				var json = JSON.stringify(command);
				ws.send(json);
				$('#deviceAddTcpModal').modal('hide');
				$('#deviceTcpAdd input').val('');
				
			}
			
		})
		
		
	}
	
	function setDeviceTcpData(data){
		$('#deviceTcpTable').bootstrapTable('load', data);
	}
	//serial设备表
	function initDeviceSerial(){
		$('.deviceTcp').addClass('hide');
		$('#deviceSerialTable').bootstrapTable({
	        method : 'post',
	        contentType : "application/x-www-form-urlencoded",
	        //url : 'query',
			//是否禁用ajax缓存
	        cache : false,
			//高
			//height : h-340,
			//隔行变色
	        striped : true,
	        // 显示分页
	        pagination : true,
	        // 默认显示条数
	        pageSize : 10,
	    	// 先显示的页码
	        pageNumber : 1,
	    	//可以选择的条数
	        pageList : [ 10, 20, 50, 100, 200, 500 ],
	    	// 是否显示列头
	        showHeader:true,
			// 是否显示列脚
	        showFooter:false,
			// 是否显示内容列下拉框
	        showColumns : true,
			// 是否显示内容列刷新
	        // showRefresh :true,
			// 是否切换显示视图
	        showToggle:true,
			// 切换显示条数页码框
	        showPaginationSwitch:false,
	        // 按钮显示左右
	        buttonsAlign:'right',
	        // 搜索
	        search : true,
			// 搜索显示左右
	        searchAlign:'left',
			// 页码显示上下
	        paginationVAlign:'bottom',
	        
	        iconsPrefix:'glyphicon',
	        icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
	        clickToSelect : true,
	        columns : [ {
	            field : "name",
	            title : "名称",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "desc",
	            title : "描述",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "slaveid",
	            title : "从机号",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	       
	        }, {
	            field : "type",
	            title : "类型",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "baudrate",
	            title : "波特率",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "bytesize",
	            title : "数据位",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "stopbits",
	            title : "停止位",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "parity",
	            title : "校验位",
	            align : "center",
	            valign : "middle",
	            sortable : "true"   
	        }, {
	            field : "timeout",
	            title : "超时",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            // field : "handle",
	            title : "操作",
	            align : "center",
	            valign : "middle",
	            events: operateIndex,
	        	formatter: deviceSerialEditDelete
	        } ],
	        data : [],
	        onPageChange : function(size, number) {
	            $("#pageSizeInput").val(size);
	            $("#pageNumberInput").val(number);
	            var form = $('#tableForm');
	            form.action = 'query';
	            form.submit();
	        },
	        
	        formatNoMatches : function() {
	            return '无符合条件的记录';
	        },
	       
	    });
		$('#serialDeviceAdd').click(function(){
			$('#deviceAddSerialModal').modal('show');
			$('#deviceAddSerialModal input').next('.red').addClass('hide');
		});
		$('#addSerialName,#addSerialDesc,#addSerialSlaveid,#addSerialPort,#addSerialOvertime').blur(function(){
			var val = $(this).val();
			//判断不为空
			if(val == '') {
				$(this).next('.red').removeClass('hide');
			//判断正则
			}else{
				$(this).next('.red').addClass('hide');
			}
		});
		$('#deviceAddSerialModal .okbtn').click(function(){
			
			var addSerialName = $('#addSerialName').val();
			var addSerialDesc = $('#addSerialDesc').val();
			var addSerialSlaveid = $('#addSerialSlaveid').val();
			
			var addSerialOvertime = $('#addSerialOvertime').val();
			var addSerialType = $('#addSerialType option:selected').text();
			var addSerialBaudrate = $('#addSerialBaudrate option:selected').text();
			var addSerialBytesize = $('#addSerialBytesize option:selected').text();
			var addSerialStop = $('#addSerialStop option:selected').text();
			var addSerialParity = $('#addSerialParity option:selected').val();
			
			if(addSerialName == '' || addSerialDesc == '' || addSerialSlaveid == '' || addSerialOvertime == ''){
				$('#deviceSerialAdd input').blur();
			}else{
				var command = new packetCommand();
				command.command = CmdDevice;
				command.id = id;
				command.name = name;
			var param = new deviceParam();
				param.cmd = CmdAdd;
				param.channelid = devicerowid;
				param.type = devicerowtype;
			var paramadd = new Device();
				paramadd.name = addSerialName;
				paramadd.desc = addSerialDesc;
				paramadd.type = addSerialType;
				paramadd.slaveid = parseInt(addSerialSlaveid);
				paramadd.baudrate = parseInt(addSerialBaudrate);
				paramadd.bytesize = parseInt(addSerialBytesize);
				paramadd.stopbits = parseInt(addSerialStop);
				paramadd.parity = addSerialParity;
				paramadd.timeout = parseInt(addSerialOvertime);
				param.device = paramadd;
				command.param = param;
			var json = JSON.stringify(command);
			ws.send(json);
			$('#deviceAddSerialModal').modal('hide');
			$('#deviceSerialAdd input').val('');
			}
		});
	}
	function setDeviceSerialData(data){
		$('#deviceSerialTable').bootstrapTable('load', data);
	}
	// 数据点列表
	function initNumberTag(){
		$('#tag-table').bootstrapTable({
	        method : 'post',
	        contentType : "application/x-www-form-urlencoded",
	        //url : 'query',
			//是否禁用ajax缓存
	        cache : false,
			//高
			//height : h-340,
			//隔行变色
	        striped : true,
	        // 显示分页
	        pagination : true,
	        // 默认显示条数
	        pageSize : 10,
	    	// 先显示的页码
	        pageNumber : 1,
	    	//可以选择的条数
	        pageList : [ 10, 20, 50, 100, 200, 500 ],
	    	// 是否显示列头
	        showHeader:true,
			// 是否显示列脚
	        showFooter:false,
			// 是否显示内容列下拉框
	        showColumns : true,
			// 是否显示内容列刷新
	        // showRefresh :true,
			// 是否切换显示视图
	        showToggle:true,
			// 切换显示条数页码框
	        showPaginationSwitch:false,
	        // 按钮显示左右
	        buttonsAlign:'right',
	        // 搜索
	        search : true,
			// 搜索显示左右
	        searchAlign:'left',
			// 页码显示上下
	        paginationVAlign:'bottom',
	        
	        iconsPrefix:'glyphicon',
	        icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
	        clickToSelect : true,
	        columns : [ {
	            field : "name",
	            title : "名称",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "desc",
	            title : "描述",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "address",
	            title : "源地址",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "span_value",
	            title : "值",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        }, {
	            field : "span_time",
	            title : "时间",
	            align : "center",
	            valign : "middle",
	            sortable : "true"
	        
	        }, {
	            // field : "handle",
	            title : "操作",
	            align : "center",
	            valign : "middle",
	            events: operateIndex,
	        	formatter: tagEditDelete
	        } ],
	        data : [],
	        onPageChange : function(size, number) {
	            $("#pageSizeInput").val(size);
	            $("#pageNumberInput").val(number);
	            var form = $('#tableForm');
	            form.action = 'query';
	            form.submit();
	        },
	        
	        formatNoMatches : function() {
	            return '无符合条件的记录';
			},
			onPageChange : function(number, size){
				tagArray = $('#tag-table').bootstrapTable('getData',true);
				 
			}
		});
		
		var command = new packetCommand();
			command.command = CmdTag;
			command.id = id;
			command.name = name;
		var param = new tagParam();
			param.cmd = query;
		var taglook = new Tag();
			taglook.deviceID = -1;
			param.tag = taglook;
			command.param = param;
		var json = JSON.stringify(command);
		ws.send(json);
		$('#addTagBtn').click(function(){
			$('#tagAddModal').modal('show');
			$('#tagAddModal input').next('.red').addClass('hide');
			$('#tagTi').addClass('hide');
			// $('#tagAddModal').on('shown.bs.modal', function (e) {
			// })
			var command = new packetCommand();
				command.command = CmdTag;
				command.id = id;
				command.name = name;
			var param = new tagParam();
				param.cmd = cmdTagDevice;
				param.tag = {};
				command.param = param;
			var json = JSON.stringify(command);
			ws.send(json);
			var command = new packetCommand();
				command.command = CmdTag;
				command.id = id;
				command.name = name;
			var param = new tagParam();
				param.cmd = cmdTagMQTT;
				param.tag = {};
				command.param = param;
			var json = JSON.stringify(command);
			ws.send(json);
			$('#tagAddModal input').blur(function(){
				var val = $(this).val();
				//判断不为空
				if(val == '') {
					$(this).next('.red').removeClass('hide');
				//判断正则
				}else{
					$(this).next('.red').addClass('hide');
				}
			});
			$('#tagValueTypeAdd').blur(function(){
				var typeval = $(this).val();
				$("#tagSortAdd").empty(); 
				if(typeval.indexOf("8") > 0 || typeval.indexOf("16") > 0){
					$('#tagSortAdd').html('<option value="AB" class="sortOne">AB</option><option value="BA" class="sortOne">BA</option>');
				}
				if(typeval.indexOf("32") > 0 || typeval.indexOf("float") > 0){
					$('#tagSortAdd').html('<option value="ABCD" class="sortTwo">ABCD</option><option value="BADC" class="sortTwo">BADC</option><option value="CDAB" class="sortTwo">CDAB</option><option value="DCBA" class="sortTwo">DCBA</option>');
				}
				if(typeval.indexOf("64") > 0 || typeval.indexOf("dou") > 0){
					$('#tagSortAdd').html('<option value="ABCDEFGH" class="sortThr">ABCDEFGH</option><option value="GHEFCDAB" class="sortThr">GHEFCDAB</option><option value="BADCFEHG" class="sortThr">BADCFEHG</option><option value="HGFEDCBA" class="sortThr">HGFEDCBA</option>');
				}
			})
			$('.addCheckbtn').click(function(){
				$(this).unbind();
				
				var tagNameAdd = $('#tagNameAdd').val();
				var tagDescAdd = $('#tagDescAdd').val();
				var tagDeviceAdd = parseInt($('#tagDeviceAdd option:selected').val());
				var tagSelfCodeAdd = $('#tagSelfCodeAdd').val();
				var tagTopicAdd = $('#tagTopicAdd').val();
				var tagReadAdd = parseInt($('#tagReadAdd option:selected').val());
				var tagValueTypeAdd = $('#tagValueTypeAdd option:selected').val();
				var tagTypeAdd = parseInt($('#tagTypeAdd option:selected').val());
				var tagSortAdd = $('#tagSortAdd option:selected').val();
				var tagPingAdd = parseInt($('#tagPingAdd').val());
				var tagK1Add = parseInt($('#tagK1Add').val());
				var tagK2Add = parseInt($('#tagK2Add').val());
				var tagHilimAdd = parseInt($('#tagHilimAdd').val());
				var tagLolimAdd = parseInt($('#tagLolimAdd').val());
				var tagExpresAdd = $('#tagExpresAdd').val();
				if($('#tagMqttAdd').val() == null){
					tagMqttAdd = [];
				}else{
					stringArray = $('#tagMqttAdd').val().toString().split(',');
					rowArray = [];
					for(var i=0;i<stringArray.length;i++){
						mqtt = parseInt(stringArray[i]);
						rowArray.push(mqtt);
	
					}
					tagMqttAdd = rowArray;
					
				}
				if(tagNameAdd == '' || tagSelfCodeAdd == '' || tagTopicAdd == ''){
					$('#tagAddModal input').blur();
					$('#tagTi').removeClass('hide');
				}else{
					$('#tagTi').addClass('hide');
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = CmdTagTest;
					var tagadd = new Tag();
						tagadd.deviceID = tagDeviceAdd;
						tagadd.type = tagTypeAdd;
						tagadd.name = tagNameAdd;
						tagadd.desc = tagDescAdd;
						tagadd.address = tagSelfCodeAdd;
						tagadd.valuetype = tagValueTypeAdd;
						tagadd.swaptype = tagSortAdd;
						tagadd.duration = tagPingAdd;
						tagadd.readwrite = tagReadAdd;
						tagadd.topic = tagTopicAdd;
						tagadd.expression = tagExpresAdd;
						tagadd.K1 = tagK1Add;
						tagadd.K2 = tagK2Add;
						tagadd.LOLIM = tagLolimAdd;
						tagadd.HILIM = tagHilimAdd;
						tagadd.mqttID = tagMqttAdd;
		
						param.tag = tagadd;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					console.log(json);
					
				}
			})
			$('#tagAddModal .okbtn').click(function(){
				$(this).unbind();
				
				var tagNameAdd = $('#tagNameAdd').val();
				var tagDescAdd = $('#tagDescAdd').val();
				var tagDeviceAdd = parseInt($('#tagDeviceAdd option:selected').val());
				var tagSelfCodeAdd = $('#tagSelfCodeAdd').val();
				var tagTopicAdd = $('#tagTopicAdd').val();
				var tagReadAdd = parseInt($('#tagReadAdd option:selected').val());
				var tagValueTypeAdd = $('#tagValueTypeAdd option:selected').val();
				var tagTypeAdd = parseInt($('#tagTypeAdd option:selected').val());
				var tagSortAdd = $('#tagSortAdd option:selected').val();
				var tagPingAdd = parseInt($('#tagPingAdd').val());
				var tagK1Add = parseInt($('#tagK1Add').val());
				var tagK2Add = parseInt($('#tagK2Add').val());
				var tagHilimAdd = parseInt($('#tagHilimAdd').val());
				var tagLolimAdd = parseInt($('#tagLolimAdd').val());
				var tagExpresAdd = $('#tagExpresAdd').val();
				var tagMqttAdd = $('#tagMqttAdd').val();
				if(tagMqttAdd == null){
					tagMqttAdd = [];
				}else{
					stringArray = $('#tagMqttAdd').val().toString().split(',');
					rowArray = [];
					for(var i=0;i<stringArray.length;i++){
						mqtt = parseInt(stringArray[i]);
						rowArray.push(mqtt);
	
					}
					tagMqttAdd = rowArray;
					
				}
				if(tagNameAdd == '' || tagSelfCodeAdd == '' || tagTopicAdd == ''){
					$('#tagAddModal input').blur();
					$('#tagTi').removeClass('hide');
				}else{
					$('#tagTi').addClass('hide');
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = CmdAdd;
					var tagadd = new Tag();
						tagadd.deviceID = tagDeviceAdd;
						tagadd.type = tagTypeAdd;
						tagadd.name = tagNameAdd;
						tagadd.desc = tagDescAdd;
						tagadd.address = tagSelfCodeAdd;
						tagadd.valuetype = tagValueTypeAdd;
						tagadd.swaptype = tagSortAdd;
						tagadd.duration = tagPingAdd;
						tagadd.readwrite = tagReadAdd;
						tagadd.topic = tagTopicAdd;
						tagadd.expression = tagExpresAdd;
						tagadd.K1 = tagK1Add;
						tagadd.K2 = tagK2Add;
						tagadd.LOLIM = tagLolimAdd;
						tagadd.HILIM = tagHilimAdd;
						tagadd.mqttID = tagMqttAdd;
		
						param.tag = tagadd;
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
					console.log(json);
					$('#tagAddModal').modal('hide');
					$('#tagAddModal input').val('');
					$('#TestResult').html("");
				}
			})

		});
		
		if(tagTimer == undefined) {
			tagTimer = setInterval(function(){
				for(var n = 0;n < tagArray.length;n++){
					var command = new packetCommand();
						command.command = CmdTag;
						command.id = id;
						command.name = name;
					var param = new tagParam();
						param.cmd = cmdTagValue;
						param.tag = tagArray[n];
						command.param = param;
					var json = JSON.stringify(command);
					ws.send(json);
				}
			}, 1000);
		}
	}
	
	// 数据点加载数据
	function setNumberTagData(data){
		$('#tag-table').bootstrapTable('load', data);
		tagArray = $('#tag-table').bootstrapTable('getData',true);
	}
	//日志
	function initLog(){
		$('#log-table').bootstrapTable({
			//toolbar: '#toolbar',
            method : 'post',
			// contentType : "application/x-www-form-urlencoded",
            //url : 'query',
			//是否禁用ajax缓存
            cache : false,
			//高
			//height : h-340,
			//隔行变色
            striped : true,
			//显示分页
            pagination : true,
			//默认显示条数
            pageSize : 10,
			//先显示的页码
            pageNumber : 1,
			//可以选择的条数
            pageList : [ 10, 20, 50, 100, 200, 500 ],
			//是否显示列头
            showHeader:true,
			//是否显示列脚
            showFooter:false,
			//是否显示内容列下拉框
            showColumns : true,
			//是否显示内容列刷新
            showRefresh :true,
			//是否切换显示视图
            showToggle:true,
			//切换显示条数页码框
            showPaginationSwitch:false,
			//按钮显示左右
            buttonsAlign:'right',
			//搜索
            search : true,
			//搜索显示左右
            searchAlign:'left',
			//页码显示上下
            paginationVAlign:'bottom',
            
            iconsPrefix:'glyphicon',
            icons:{
					paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
					paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
					refresh: 'glyphicon-refresh icon-refresh',
					toggle: 'glyphicon-list-alt icon-list-alt',
					columns: 'glyphicon-th icon-th',
					detailOpen: 'glyphicon-plus icon-plus',
					detailClose: 'glyphicon-minus icon-minus',
					},
            clickToSelect : true,
            columns : [ {
                field : "type",
                title : "类型",
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "time",
                title : "时间",
                width : 180,
                align : "center",
                valign : "middle",
                sortable : "true"
            }, {
                field : "content",
                title : "内容",
                align : "left",
                valign : "middle",
                sortable : "true"
            }],
            data : [],
            onPageChange : function(size, number) {
                $("#pageSizeInput").val(size);
                $("#pageNumberInput").val(number);
                var form = $('#tableForm');
                form.action = 'query';
                form.submit();
            },
            
            formatNoMatches : function() {
                return '无符合条件的记录';
			}
		
        });
		var command = new packetCommand();
			command.command = CmdLog;
			command.id = id;
			command.name = name;
			command.param = {};
		var json = JSON.stringify(command);
		ws.send(json);
	}
	function setLogData(data){
		$('#log-table').bootstrapTable('load', data);
	}
	
	//右侧切换内容initRuntimeInfo
	function  ids(file){
		if(file){
			$.ajax({  
	        type:"GET",
	        url:"./rpublic/"+file,  
	        dataType: "html",  
	        success: function(data){ 
		           	$('.jiazai').hide();
		           	$('.error').hide();
	           		$('.public')[0].innerHTML = data;
	           		if(file == 'home'){
						   initHome();
						   initGatewayInfo();
						
	           		}
	           		if(file == 'mqsys'){
	           			initMqtt();
	           			
	           		}
	           		if(file == 'task'){
	           			initChannel();
	           			$('#breadcrumb .point').click(function(){
							listid = $(this).attr('id');
							task(listid);
							$('#task-device').addClass('hide');
							
						});
					}
					if(file == 'tag'){
						initNumberTag();
						
					}
	           		if(file == 'log'){
	           			initLog();
	           		}
	           		if(file == 'system'){
						initSystemConfig();
	           		}
	           		if(file == 'user'){
	           			initUser();
	           		}
		        }  ,
	        error:function(data){
		        	$('.error').show();
		        	$('.jiazai').hide();
		        }
	   		});
		}else{
			$('.error').show();
        	$('.jiazai').hide();
		}
	}

	//任务切换
	function  task(content,type,name){
		if(content){
			$.ajax({  
	        type:"GET",
	        url:"./rpublic/"+content,  
	        dataType: "html",  
	        success: function(data){ 
		           	$('.jiazai').hide();
		           	$('.error').hide();
	           		$('.listdiv')[0].innerHTML = data;
	           		if(content == 'task-channel'){
	           			initChannel();
	           		}
	           		if(content == 'task-device'){
	           			if(type == "tcp"){
							   initDeviceTcp();
							   $('#tcpName').html(name);
	           				
	           			}
	           			if(type == "serial"){
							   initDeviceSerial();
							   $('#serialName').html(name);
	           				
	           			}
	           			
	           		}
	           		
	           		
		        }  ,
	        error:function(data){
		        	$('.error').show();
		        	$('.jiazai').hide();
		        }
	   		});
		}else{
			$('.error').show();
        	$('.jiazai').hide();
		}
	}

});